package com.hivekion.common.scheduled;

import com.hivekion.system.mapper.SysDataBaseMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;

/**
 * @authot morning
 * @date 2021/8/4 9:44
 */
@Service
public class BackUpDataBaseManager {

    private static final Logger log = LoggerFactory.getLogger(BackUpDataBaseManager.class);

    @Autowired
    private SysDataBaseMapper dataBaseMapper;

    @Value("${spring.datasource.dynamic.datasource.mysql.driver-class-name}")
    private String driverClassName;
    @Value("${spring.datasource.dynamic.datasource.mysql.url}")
    private String url;
    @Value("${spring.datasource.dynamic.datasource.mysql.username}")
    private String userName;
    @Value("${spring.datasource.dynamic.datasource.mysql.password}")
    private String password;
    @Value("${uploadPath.projectfile}")
    public String uploadPath;
    @Value("${mysqlPath.projectfile}")
    public String mysqlPath;

    /**
     * 获取数据库名
     */
    public String getDataBaseName() {
        return url.substring(url.indexOf("3306"), url.indexOf("?")).replaceAll("/", "").replaceAll("3306", "");
    }

    /**
     * 获取主机地址
     */
    private String getHost() {
        return url.substring(url.indexOf("mysql"), url.indexOf("3306")).replace(":", "").replace("//", "").replace("mysql", "");
    }

    /**
     * 导出 sql 并返回相关信息
     */
    public void exportSql(String time) {
        // 指定导出的 sql 存放的文件夹
        File saveFile = new File(uploadPath);
        if (!saveFile.exists()) {
            saveFile.mkdirs();
        }

        String host = getHost();
        String dataBaseName = getDataBaseName();
        String fileName = time + "_" + "cloudpm.sql";

        StringBuilder sb = new StringBuilder();
        // 拼接备份命令
        sb.append("mysqldump").append(" --opt").append(" -h ").append(host).append(" --user=").append(userName).append(" --password=").append(password);
        sb.append(" --result-file=").append(uploadPath + fileName).append(" --default-character-set=utf8 ").append(dataBaseName);
        System.out.println(sb.toString());
        try {
            Process exec = Runtime.getRuntime().exec(sb.toString());
            if (exec.waitFor() == 0) {
                log.info("数据库备份成功，保存路径：" + uploadPath);
            } else {
                System.out.println("process.waitFor()=" + exec.waitFor());
            }
        } catch (IOException e) {
            log.error("备份 数据库 出现 IO异常 ", e);
        } catch (InterruptedException e) {
            log.error("备份 数据库 出现 线程中断异常 ", e);
        } catch (Exception e) {
            log.error("备份 数据库 出现 其他异常 ", e);
        }
    }

    /**
     * 导出表数据 sql
     *
     * @param tableName
     */
    public String exportTableDataSql(String tableName) {
        String sqlDataPath = uploadPath + "/" + tableName + ".sql";
        File file = new File(uploadPath);
        if (!file.exists()) {
            file.mkdirs();
        }
        Runtime runtime = Runtime.getRuntime();
        String command = getExportTableDataCommand(tableName, sqlDataPath);
        try {
            Process exec = runtime.exec(command);
            if (exec.waitFor() == 0){
                return sqlDataPath;
            }else {
                return "";
            }
        } catch (IOException e) {
            log.error("导出数据库表数据出现IO异常",e);
            return "";
        }catch (InterruptedException e){
            log.error("导出数据库表数据出现IO异常",e);
            return "";
        }
    }

    /**
     * 导出sql数据mysqldump命令
     *
     * @param tableName
     * @param sqlDataPath
     * @return
     */
    public String getExportTableDataCommand(String tableName, String sqlDataPath) {
        String mysqlName = getDataBaseName();
        String host = getHost();
        String sqlPath = dataBaseMapper.selectDataDir();
        if (sqlPath.contains(" ") || sqlPath.indexOf(" ") > -1){
            sqlPath = mysqlPath;
        }
        StringBuffer command = new StringBuffer();
        command.append("cmd /c ");
        command.append(sqlPath.replace("data","bin").replace("Data","bin"));
        command.append("\\mysqldump -h " + host).append(" -u" + userName).append(" -p" + password)
                .append(" -t --extended-insert=false ").append(mysqlName).append(" " + tableName)
                .append(">" + sqlDataPath);
        return command.toString();
    }

}
